/*
 * TimerDrv.c
 *
 * Created: 08.02.2013 19:34:54
 *  Author: victor
 */

/*The 16 bit Timer1 will ensure the base time for the entire system scheduler*/

/* Module's includes */
#include <avr/io.h>
#include <avr/interrupt.h>
#include <TimerDrv.h>
#include <Basetypes.h>
#include <TSystem.h>
#include <OutputHdl.h>
/* Module's definitions */
/* 256 prescaller with 11059200 clock=>43.2 value for the counter to result a 1ms */
#define TIMERDRV_C_1MS_T2_U8  (u8)43

static u8 TimerDrv_TimerSetFlag_u8 = ZERO ;

/* Module's function definitions */
/* initialization function for the timer */
void TimerDrv_Init ( void )
{
	/* Timer 2 for system timing */
	/* CTC mode and 256 prescaller with 11059200 clock=>43.2 value for the counter to result a 1ms */
	TCCR2 = ( 1 << WGM21 ) | ( 1 << CS22 ) | ( 1 << CS21 ) ;
	/* Enable the Timer output compare match interrupt */
	TIMSK |= ( 1 << OCIE2 );
	/* Set the Compare value to match 1ms */
	OCR2 = TIMERDRV_C_1MS_T2_U8;
	
	/*Timer 1 used for BTT ON/OFF button timing*/
	/* CTC mode */
	TCCR1B |= ( 1 << WGM12 );
	/* enable the interrupt for timer2 compare match */
	TIMSK |= ( 1 << OCIE1A);
	/* 1024 prescaler with 11059200 clock=>55000 value for the counter to result a 5ms */
	TCCR1B |= ( 1 << CS10 ) | ( 1 << CS12 );
}

/* 1 ms interrupt routine as base time for the software */
ISR ( TIMER2_COMP_vect )
{
	TSystem_1msTask();
}

void TimerDrv_ResetTimer1(u8 SecondsToCount)
{
	if ( ZERO != TimerDrv_TimerSetFlag_u8 )
	{
		/*do nothing and exit*/
	}
	else
	{
	/* Normal port operation since if port driven by timer, will ignore the port manipulation operations */	
	/* Fill the value to be compared into the compare register */
	/* 1024 prescaler with 11059200 clock=>55000 value for the counter to result a 5ms */
	OCR1A = SecondsToCount * 11000 ;
	/* Resets the counter value */
	TCNT1 = ZERO;
	TCCR1B |= ( 1 << CS10 ) | ( 1 << CS12 );
	TimerDrv_TimerSetFlag_u8 = 1;
	}
}

/* interrupt routine for the timer1 setup standby */
ISR ( TIMER1_COMPA_vect )
{
		/* stop clock source for timer */
		TCCR1B &= ~(( 1 << CS10 ) | ( 1 << CS12 ));
		/* Set PD5 to LOW */
		DIODrv_ClearPin( POWER_ON_EN ) ;
		TimerDrv_TimerSetFlag_u8 = ZERO;
}